package com.pactera.asmp.server.config;

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

@Configuration
public class SchedulerConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${quartz.file}")
    private String quartzProperties;

    @Bean(name="schedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setStartupDelay(1);
        factory.setQuartzProperties(quartzProperties());
        SpringQuartzJobFactory jobFactory = new SpringQuartzJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        factory.setJobFactory(jobFactory);
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource(quartzProperties));
        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /*
     * quartz初始化监听器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
       return new QuartzInitializerListener();
    }

    /*
     * 通过SchedulerFactoryBean获取Scheduler的实例
     */
    @Bean(name="scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }

//    @Bean(name = "Scheduler")
//    public SchedulerFactoryBean schedulerFactoryBean(Trigger trigger) {
//        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
//        // 用于quartz集群，QuartzScheduler启动时更新已存在的job
//        factoryBean.setOverwriteExistingJobs(true);
//        // 延时启动，应用启动1秒后
//        factoryBean.setStartupDelay(1);
//        // 注册触发器
//        factoryBean.setTriggers(trigger);
//        // Spring依赖注入为null
//        SpringQuartzJobFactory jobFactory = new SpringQuartzJobFactory();
//        jobFactory.setApplicationContext(applicationContext);
//        factoryBean.setJobFactory(jobFactory);
//        return factoryBean;
//    }

}
